/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PatientTab.java
 *
 * Created on Aug 25, 2011, 2:30:51 AM
 */
package patientManager;

//import laptrinhmang.RemedyScheduler;
import app.Global;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Fun
 */
public class PatientTab extends javax.swing.JFrame {

    Vector vData1;
    Vector vColumn1;
    Vector vData2;
    Vector vColumn2;

    /** Creates new form PatientTab */
    public PatientTab() {
        initComponents();
        initPatient();
    }

    // temporary fix to work with other parts, this class should be JPanel
    public JPanel getPanel() {
        return jPanel12;
    }

    void initPatient() {
        btnReset.setEnabled(false);
        vData1 = new Vector();
        vColumn1 = new Vector();
        Connection cn = Global.getConnection();
        Statement st = null;
        ResultSet rs = null;
        try {
            st = cn.createStatement();
            rs = st.executeQuery(
                    "SELECT id, firstname, lastname, address, mobile, email"
                    + " FROM patients");
            ResultSetMetaData rsmt = rs.getMetaData();
            for (int i = 1; i <= rsmt.getColumnCount(); i++) {
                if (i == 2) {
                    vColumn1.add("PatientName");
                    i++;
                } else {
                    vColumn1.add(rsmt.getColumnName(i));
                }
            }
            while (rs.next()) {
                Vector vRow1 = new Vector();
                for (int i = 1; i <= rsmt.getColumnCount(); i++) {
                    if (i == 2) {
                        vRow1.add(rs.getString(i) + " " + rs.getString(i + 1));
                        i++;
                    } else {
                        vRow1.add(rs.getString(i));
                    }
                }
                vData1.add(vRow1);
            }

            tbl4.setModel(new DefaultTableModel(vData1, vColumn1) {

                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            });
        } catch (SQLException ex) {
            Logger.getLogger(PatientTab.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                rs.close();
                st.close();
                cn.close();
            } catch (SQLException ex) {
                Logger.getLogger(PatientTab.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        btnReset.setEnabled(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        popMenu = new javax.swing.JPopupMenu();
        updateMenu = new javax.swing.JMenuItem();
        viewdetailMenu = new javax.swing.JMenuItem();
        jPanel12 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        tbl4 = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        btnSearch = new javax.swing.JButton();
        txtMobile = new javax.swing.JTextField();
        btnReset = new javax.swing.JButton();
        btnUpdate = new javax.swing.JButton();
        btnUpdate1 = new javax.swing.JButton();
        txtAddress = new javax.swing.JTextField();
        txtName = new javax.swing.JTextField();
        txtEmail = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        updateMenu.setText("update");
        updateMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateMenuActionPerformed(evt);
            }
        });
        popMenu.add(updateMenu);

        viewdetailMenu.setText("viewdetail");
        viewdetailMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewdetailMenuActionPerformed(evt);
            }
        });
        popMenu.add(viewdetailMenu);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel12.setBorder(javax.swing.BorderFactory.createTitledBorder("Patient Management"));
        jPanel12.setPreferredSize(new java.awt.Dimension(888, 600));

        tbl4.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tbl4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbl4MouseClicked(evt);
            }
        });
        jScrollPane4.setViewportView(tbl4);

        jButton3.setText("New Patient");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        btnReset.setText("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        btnUpdate.setText("Update");
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        btnUpdate1.setText("Delete(s)");
        btnUpdate1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdate1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Address : ");

        jLabel2.setText("Name : ");

        jLabel3.setText("Email : ");

        jLabel4.setText("Mobile : ");

        javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
        jPanel12.setLayout(jPanel12Layout);
        jPanel12Layout.setHorizontalGroup(
            jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel12Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 849, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
            .addGroup(jPanel12Layout.createSequentialGroup()
                .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel12Layout.createSequentialGroup()
                        .addGap(64, 64, 64)
                        .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(jPanel12Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel12Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(33, 33, 33)
                                .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel12Layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3)
                        .addGap(35, 35, 35)))
                .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel12Layout.createSequentialGroup()
                        .addComponent(btnUpdate1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                        .addComponent(btnSearch)
                        .addGap(28, 28, 28)
                        .addComponent(btnReset)
                        .addGap(58, 58, 58)
                        .addComponent(btnUpdate)
                        .addGap(275, 275, 275))
                    .addGroup(jPanel12Layout.createSequentialGroup()
                        .addGap(227, 227, 227)
                        .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3))
                        .addGap(55, 55, 55)
                        .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtMobile, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(188, 188, 188))))
        );
        jPanel12Layout.setVerticalGroup(
            jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel12Layout.createSequentialGroup()
                .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel12Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(34, 34, 34)
                        .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1)
                            .addComponent(txtMobile, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addGap(92, 92, 92))
                    .addGroup(jPanel12Layout.createSequentialGroup()
                        .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnReset)
                            .addComponent(btnUpdate)
                            .addComponent(btnUpdate1)
                            .addComponent(btnSearch)
                            .addComponent(jButton3))
                        .addGap(18, 18, 18)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(21, Short.MAX_VALUE)
                .addComponent(jPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, 888, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, 509, Short.MAX_VALUE)
                .addGap(22, 22, 22))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        new PatientInsert(this, true);
        initPatient();
}//GEN-LAST:event_jButton3ActionPerformed

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        // TODO add your handling code here:
        vColumn2 = new Vector();
        vData2 = new Vector();

        Connection cn = Global.getConnection();
        Statement st = null;
        ResultSet rs = null;
        try {
            st = cn.createStatement();
            String sql = "Select id, firstname, lastname, address, mobile, email from patients where 1 = 1 ";
            if (!txtName.getText().trim().equals("")) {
                sql += " and (firstname like '%" + txtName.getText() + "%'";
                sql += " or lastname like '%" + txtName.getText() + "%')";
            }
            if (!txtAddress.getText().trim().equals("")) {
                sql += " and address like '%" + txtAddress.getText() + "%'";
            }
            if (!txtMobile.getText().trim().equals("")) {
                sql += " and mobile like '%" + txtMobile.getText() + "%'";
            }
            if (!txtEmail.getText().trim().equals("")) {
                sql += " and email like '%" + txtEmail.getText() + "%'";
            }
//            System.out.println(sql);
            rs = st.executeQuery(sql);
            ResultSetMetaData rsmt = rs.getMetaData();
            for (int i = 1; i <= rsmt.getColumnCount(); i++) {
                if (i == 2) {
                    vColumn2.add("PatientName");
                    i++;
                } else {
                    vColumn2.add(rsmt.getColumnName(i));
                }
            }
            while (rs.next()) {
                Vector vRow = new Vector();
                for (int i = 1; i <= rsmt.getColumnCount(); i++) {
                    if (i == 2) {
                        vRow.add(rs.getString(i) + " " + rs.getString(i + 1));
                        i++;
                    } else {
                        vRow.add(rs.getString(i));
                    }
                }
                vData2.add(vRow);
            }
            tbl4.setModel(new DefaultTableModel(vData2, vColumn2) {

                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            });
            txtAddress.setText("");
            txtEmail.setText("");
            txtMobile.setText("");
            txtName.setText("");
        } catch (SQLException ex) {
            Logger.getLogger(PatientTab.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                rs.close();
                st.close();
                cn.close();
            } catch (SQLException ex) {
                Logger.getLogger(PatientTab.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
}//GEN-LAST:event_btnSearchActionPerformed

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        // TODO add your handling code here:
        initPatient();
}//GEN-LAST:event_btnResetActionPerformed

    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        // TODO add your handling code here:
        int row = tbl4.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "No row selected !!!");
        } else {
            Vector resutl = (Vector) vData1.get(row);
            int id = Integer.parseInt(resutl.get(0).toString());
            //            System.out.println(id);
            new PatientUpdate(this, true, id);
            initPatient();
        }
}//GEN-LAST:event_btnUpdateActionPerformed

    private void btnUpdate1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdate1ActionPerformed

        int[] rows = tbl4.getSelectedRows();
        if (rows.length == 0) {
            JOptionPane.showMessageDialog(this, "No row selected");
            return;
        }
        int option = JOptionPane.showConfirmDialog(this, "ARE YOU SURE ? ");
        if (option == JOptionPane.YES_OPTION) {
            int[] rows_arr = new int[rows.length];
            int j = 0;
            for (int i : rows) {
                Vector resutl = (Vector) vData1.get(i);
                rows_arr[j++] = Integer.parseInt(resutl.get(0).toString());
            }
            String id = "";
            for (int i : rows_arr) {
                id += i + ",";
            }
            id = id.substring(0, id.length() - 1);
            Connection cn = Global.getConnection();
            Statement st = null;
            try {
                st = cn.createStatement();
                int count = st.executeUpdate("DELETE  patients WHERE id in (" + id + ")");
                if (count > 0) {
                    JOptionPane.showMessageDialog(this, "SUCCESSFUL!!!");
                    initPatient();
                } else {
                    JOptionPane.showMessageDialog(this, "UNSUCCESSFUL!!!");
                }
            } catch (SQLException ex) {
                Logger.getLogger(PatientTab.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    st.close();
                    cn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(PatientTab.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_btnUpdate1ActionPerformed

    private void tbl4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl4MouseClicked
        popMenu.show(evt.getComponent(), evt.getX(), evt.getY());
}//GEN-LAST:event_tbl4MouseClicked

    private void updateMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateMenuActionPerformed
        // TODO add your handling code here:
        int row = tbl4.getSelectedRow();
        Vector resutl = (Vector) vData1.get(row);
        int id = Integer.parseInt(resutl.get(0).toString());
        //            System.out.println(id);
        new PatientUpdate(this, true, id);
        initPatient();

    }//GEN-LAST:event_updateMenuActionPerformed

    private void viewdetailMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewdetailMenuActionPerformed
        // TODO add your handling code here:
        int row = tbl4.getSelectedRow();
        Vector resutl = (Vector) vData1.get(row);
        int id = Integer.parseInt(resutl.get(0).toString());
        //            System.out.println(id);
        new PatientDetail(this, true, id);
        initPatient();
    }//GEN-LAST:event_viewdetailMenuActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSearch;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JButton btnUpdate1;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JPopupMenu popMenu;
    private javax.swing.JTable tbl4;
    private javax.swing.JTextField txtAddress;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtMobile;
    private javax.swing.JTextField txtName;
    private javax.swing.JMenuItem updateMenu;
    private javax.swing.JMenuItem viewdetailMenu;
    // End of variables declaration//GEN-END:variables
}
